/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shaman.storage.impl.util;

import java.util.Iterator;
import shaman.storage.impl.file.IterationException;

/**
 *
 * @author dmitriy
 */
public class FilterIterator<T> implements Iterator<T> {

    protected final Iterator<? extends T> baseIter;
    private boolean iterFinished=false;

    public FilterIterator(Iterator<? extends T> baseIter) {
        this.baseIter=baseIter;
    }

    public boolean hasNext() throws IterationException {
        if (iterFinished)
            return false;
        boolean baseHasNext;
        try {
            baseHasNext=baseIter.hasNext();
        } catch (IterationException ex) {
            endIteration();
            throw ex;
        } catch (Throwable t) {
            endIteration();
            throw new IterationException(t);
        }
        if (!baseHasNext) endIteration();
        return baseHasNext;
    }

    public T next() throws IterationException
    {
        if (iterFinished)
            return null;
        T baseNext;
        try {
            baseNext=baseIter.next();
        } catch (IterationException ex) {
            endIteration();
            throw ex;
        } catch (Throwable t) {
            endIteration();
            throw new IterationException(t);
        }
        if (baseNext==null) endIteration();
        else elementFound(baseNext);
        return baseNext;
    }

    public void remove() {
        baseIter.remove();
    }

    private void endIteration() {
        iterFinished=true;
        iterationEnded();
    }

    protected void elementFound(T element) {
    }

    protected void iterationEnded() {
    }

}
